# validate_json.py
import json
import logging
from jsonschema import validate, ValidationError
from termcolor import colored

# 配置日志
logging.basicConfig(
    filename='json_validation.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

# 定义JSON Schema
COMMAND_SCHEMA = {
    "type": "object",
    "properties": {
        "command": {"type": "string"},
        "params": {
            "type": "object",
            "properties": {
                "width": {"type": "number", "minimum": 0},
                "height": {"type": "number", "minimum": 0},
                "radius": {"type": "number", "minimum": 0},
                "center": {
                    "type": "array",
                    "items": {"type": "number"},
                    "minItems": 2,
                    "maxItems": 2
                }
            },
            "required": ["center"]
        },
        "layer": {"type": "string"}
    },
    "required": ["command", "params"]
}

# 允许的命令列表
ALLOWED_COMMANDS = ["CIRCLE", "RECTANGLE", "LINE", "POLYGON"]


def validate_json(input_str: str) -> dict:
    """执行多级验证"""
    # 1. 基础语法验证
    try:
        data = json.loads(input_str)
        print(colored("✓ 基础语法验证通过", "green"))
    except json.JSONDecodeError as e:
        print(colored(f"✗ JSON语法错误：{str(e)}", "red"))
        return None

    # 2. 结构验证
    try:
        validate(instance=data, schema=COMMAND_SCHEMA)
        print(colored("✓ 结构验证通过", "green"))
    except ValidationError as e:
        print(colored(f"✗ 结构验证失败：{e.message}", "red"))
        print(f"错误路径：{' -> '.join(map(str, e.path))}")
        return None

    # 3. 领域验证
    errors = []
    if data["command"] not in ALLOWED_COMMANDS:
        errors.append(f"不支持的命令：{data['command']}")

    if data["command"] == "CIRCLE" and "radius" not in data["params"]:
        errors.append("圆形必须包含radius参数")

    if data["command"] == "RECTANGLE" and ("width" not in data["params"] or "height" not in data["params"]):
        errors.append("矩形必须包含width和height参数")

    if errors:
        print(colored("✗ 领域验证失败：", "red"))
        for error in errors:
            print(f"  • {error}")
        return None

    print(colored("✓ 所有验证通过！", "green", attrs=["bold"]))
    return data


def main():
    print("""CAD命令验证工具
输入说明：
1. 直接粘贴JSON内容
2. 输入空行结束输入
3. 输入 'exit' 退出程序""")

    while True:
        # 获取多行输入
        lines = []
        print("\n" + "=" * 40)
        print("请输入要验证的JSON内容：")
        while True:
            line = input()
            if line.lower() == 'exit':
                return
            if not line:
                break
            lines.append(line)

        if not lines:
            continue

        input_str = '\n'.join(lines)
        print("\n验证结果：")

        # 执行验证
        result = validate_json(input_str)

        # 记录日志
        if result:
            logging.info("验证通过：%s", json.dumps(result))
        else:
            logging.warning("验证失败：%s", input_str)


if __name__ == "__main__":
    main()